package com.zxl.study.service.impl;

import com.zxl.study.model.vo.MetaDatabaseTreeAggResultVo;
import com.zxl.study.model.vo.MetaDatabaseTreeAggVo;
import com.zxl.study.service.MetaTableService;
import com.zxl.study.support.Constants;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MetaServiceImpl implements MetaTableService {
    @Override
    public List<MetaDatabaseTreeAggResultVo> findSchemaAndInitials(List<MetaDatabaseTreeAggVo> aggList) {
        // 获取 模式，首字母，数量列表
        if (!CollectionUtils.isEmpty(aggList)) {
            if (StringUtils.isNotEmpty(aggList.get(0).getSchemaName())) {
                // 有模式
                // 按照schemaName进行拆分
                Map<String, List<MetaDatabaseTreeAggVo>> groupedItems = new HashMap<>();
                for (MetaDatabaseTreeAggVo vo : aggList) {
                    String schemaName = vo.getSchemaName();
                    if (!groupedItems.containsKey(schemaName)) {
                        groupedItems.put(schemaName, new ArrayList<>());
                    }
                    groupedItems.get(schemaName).add(vo);
                }
                // 拼接父子结构返回
                List<MetaDatabaseTreeAggResultVo> resultList = new ArrayList<>();
                for (String key : groupedItems.keySet()) {
                    MetaDatabaseTreeAggResultVo metaDatabaseTreeAggResultVo = new MetaDatabaseTreeAggResultVo();
                    metaDatabaseTreeAggResultVo.setType(Constants.TABLE_AGG_TREE_TYPE_SCHEMA);
                    metaDatabaseTreeAggResultVo.setName(key);
                    metaDatabaseTreeAggResultVo.setChildren(setAggTree(groupedItems.get(key)));
                    resultList.add(metaDatabaseTreeAggResultVo);
                }
                return resultList;
            } else {
                // 没有模式
                return setAggTree(aggList);
            }
        }
        return null;
    }
    /**
     * 拼接树形结构
     *
     * @param metaDatabaseTreeAggVos 查询聚合集合
     * @return List<MetaDatabaseTreeAggResultVo> 组装结果集
     */
    private List<MetaDatabaseTreeAggResultVo> setAggTree(List<MetaDatabaseTreeAggVo> metaDatabaseTreeAggVos) {
        //是否追加分组节点，默认不追加，超出500限制追加
        boolean isAppendNode = Boolean.FALSE;
        // 数量临时变量，用于判断是否超过了500
        int numStay = 0;
        // 首字母临时变量，用于拼接返回的a-f
        String initialStart = "";
        String initialEnd = "";
        List<MetaDatabaseTreeAggResultVo> resultList = new ArrayList<>();
        for (int i = 0; i < metaDatabaseTreeAggVos.size(); i++) {
            MetaDatabaseTreeAggVo metaDatabaseTreeAggVo = metaDatabaseTreeAggVos.get(i);
            // 首字母
            String initial = metaDatabaseTreeAggVo.getInitial();
            // 数量
            Integer nums = metaDatabaseTreeAggVo.getNums();
            if (nums > Constants.TABLE_AGG_TREE_NUMS) {
                //如果当前行超出限制
                isAppendNode = Boolean.TRUE;
                //添加已记录的分组节点
                addTreeNode(initialStart, initialEnd, resultList);

                //记录本行父级
                MetaDatabaseTreeAggResultVo metaDatabaseTreeAggResultVoHad = new MetaDatabaseTreeAggResultVo();
                metaDatabaseTreeAggResultVoHad.setName(initial);
                metaDatabaseTreeAggResultVoHad.setType(Constants.TABLE_AGG_TREE_TYPE_INITIAL);
                // 拆分本行1-500，501-1000
                metaDatabaseTreeAggResultVoHad.setChildren(setAggNums(nums));
                resultList.add(metaDatabaseTreeAggResultVoHad);

                //清空临时变量
                numStay = 0;
                initialStart = "";
                initialEnd = "";
            } else if (numStay + nums > Constants.TABLE_AGG_TREE_NUMS) {
                //如果当前行加累计数量超出限制
                isAppendNode = Boolean.TRUE;
                //添加已记录的分组节点
                addTreeNode(initialStart, initialEnd, resultList);

                //设置当前行信息为初始值
                numStay = nums;
                initialStart = initial;
                initialEnd = "";
            } else {
                // 如果本行没有超500,并且相加也没有超500
                numStay += nums;
                if (StringUtils.isEmpty(initialStart)) {
                    initialStart = initial;
                } else {
                    initialEnd = initial;
                }
            }

            // 最后一次遍历，未添加的都添加掉，若总数量未超限制则不添加
            if (i == metaDatabaseTreeAggVos.size() - 1 && numStay != 0 && isAppendNode) {
                addTreeNode(initialStart, initialEnd, resultList);
            }
        }
        return resultList;
    }
    /**
     * 设置虚拟树的1-500，501-1000结构
     *
     * @param nums 表数量
     * @return List<MetaDatabaseTreeAggResultVo> 1-500，501-1000层的集合
     */
    private List<MetaDatabaseTreeAggResultVo> setAggNums(Integer nums) {
        List<MetaDatabaseTreeAggResultVo> metaDatabaseTreeAggResultVos = new ArrayList<>();
        // 拆分为1-500，501-1000,1001结构
        int quotient = nums / Constants.TABLE_AGG_TREE_NUMS;
        int remainder = nums % Constants.TABLE_AGG_TREE_NUMS;
        for (int i = 1; i <= quotient; i++) {
            MetaDatabaseTreeAggResultVo metaDatabaseTreeAggResultVo = new MetaDatabaseTreeAggResultVo();
            int start = (i - 1) * Constants.TABLE_AGG_TREE_NUMS + 1;
            int end = i * Constants.TABLE_AGG_TREE_NUMS;
            metaDatabaseTreeAggResultVo.setName(start + "-" + end);
            metaDatabaseTreeAggResultVo.setType(Constants.TABLE_AGG_TREE_TYPE_NUM);
            metaDatabaseTreeAggResultVos.add(metaDatabaseTreeAggResultVo);
        }
        if (remainder > 0) {
            MetaDatabaseTreeAggResultVo metaDatabaseTreeAggResultVo = new MetaDatabaseTreeAggResultVo();
            if (remainder == 1) {
                metaDatabaseTreeAggResultVo.setName(nums.toString());
            } else {
                metaDatabaseTreeAggResultVo.setName((quotient * Constants.TABLE_AGG_TREE_NUMS + 1) + "-" + nums);
            }
            metaDatabaseTreeAggResultVo.setType(Constants.TABLE_AGG_TREE_TYPE_NUM);
            metaDatabaseTreeAggResultVos.add(metaDatabaseTreeAggResultVo);
        }
        return metaDatabaseTreeAggResultVos;
    }

    /**
     * 追加树节点
     *
     * @param initialStart 初始位置
     * @param initialEnd   结束位置
     * @param resultList   分组存储集合（根据引用追加值）
     * @return void
     */
    private void addTreeNode(String initialStart, String initialEnd, List<MetaDatabaseTreeAggResultVo> resultList) {
        if (StringUtils.isNotEmpty(initialStart) || StringUtils.isNotEmpty(initialEnd)) {
            MetaDatabaseTreeAggResultVo metaDatabaseTreeAggResultVoHad = new MetaDatabaseTreeAggResultVo();
            if (initialStart.equals(initialEnd) || StringUtils.isEmpty(initialEnd)) {
                metaDatabaseTreeAggResultVoHad.setName(initialStart);
            } else {
                metaDatabaseTreeAggResultVoHad.setName(initialStart.concat("-").concat(initialEnd));
            }
            metaDatabaseTreeAggResultVoHad.setType(Constants.TABLE_AGG_TREE_TYPE_INITIAL);
            resultList.add(metaDatabaseTreeAggResultVoHad);
        }
    }
}
